package com.demo.modules.stock.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.exception.RRException;
import com.demo.modules.stock.entity.StockInfoEntity;
import com.demo.modules.stock.service.StockInfoService;
import com.demo.modules.stock.util.StockUtils;
import com.demo.modules.sys.controller.AbstractController;
import com.demo.utils.PageUtils;
import com.demo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@RequestMapping("/stockInfo")
public class StockInfoController extends AbstractController {

    @Autowired
    StockInfoService stockInfoService;

    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        logger.debug("查询股票基本信息,参数:{}", JSON.toJSONString(params));
        PageUtils page = stockInfoService.queryPage(params);
        return R.ok().put("page", page);
    }

    @RequestMapping("/allStockCode")
    public R allStockCode() {
        logger.debug("查询所有股票Code和名称");
        return R.ok().put("list", stockInfoService.list(new QueryWrapper<StockInfoEntity>().select("STOCK_CODE,STOCK_NAME")));
    }

    @RequestMapping("/industry")
    public R industry() {
        logger.debug("查询所有的深圳板块");
        List<StockInfoEntity> list = stockInfoService.list(new QueryWrapper<StockInfoEntity>()
                .select("DISTINCT(industry)").eq("stock_exchange", "sz").orderByAsc("industry"));
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setId(i + "");
        }
        return R.ok().put("list", list);
    }

    /**
     * 深圳证券交易所下载的股票信息中有板块信息，而上证交易所没有，所以从网上爬取上证交易所股票的板块信息更新到数据库
     *
     * @return 更新时长
     */
    @RequestMapping("/updateShanghaiStockExchangeIndustry")
    public R updateShanghaiStockExchangeIndustry() {
        Date start = new Date();
        logger.debug("获取深圳证券交易所的板块名称");
        List<StockInfoEntity> industryTypeList = stockInfoService.list(new QueryWrapper<StockInfoEntity>()
                .select("DISTINCT(industry)").eq("stock_exchange", "sz").orderByAsc("industry"));
        String industryType;
        for (StockInfoEntity tmp : industryTypeList) {
            industryType = tmp.getIndustry().substring(0, 1);
            logger.debug("根据股票类型(如A代表农林牧渔)获取该股票板块的所有股票code并更新数据库,板块类型{}", industryType);
            List<String> code = StockUtils.getIndustryCode(industryType);
            for (String c : code) {
                StockInfoEntity updateStock = stockInfoService.getOne(new QueryWrapper<StockInfoEntity>().eq("stock_code", c));
                if (updateStock != null) {
                    updateStock.setIndustry(tmp.getIndustry());
                    stockInfoService.updateById(updateStock);
                }
            }
        }
        Date end = new Date();
        return R.ok().put("loadTime", DateUtil.between(start, end, DateUnit.MINUTE));
    }

    /**
     * 删除所有股票信息
     */
    @RequestMapping("/deleteAllStock")
    public R deleteAllStock() {
        stockInfoService.remove(new QueryWrapper<>());
        return R.ok();
    }

    /**
     * 导入股票基础信息
     */
    @RequestMapping("/importFile")
    public R upload(@RequestParam("file") MultipartFile file, @RequestParam(required = false) String stockExchange) throws Exception {
        logger.debug("导入上交所和深交所股票信息文件");
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<StockInfoEntity> list = new ArrayList<>();
        List<Map<String, Object>> mapList = reader.readAll();
        if ("sh".equals(stockExchange)) {
            //上交所股票信息
            for (Map<String, Object> m : mapList) {
                Object[] itemArray = m.values().toArray();
                StockInfoEntity item = new StockInfoEntity();
                item.setStockCode(itemArray[0].toString().trim());//股票code
                item.setStockName(itemArray[1].toString().trim());//股票名字
                item.setListingDate(itemArray[4].toString().trim()); //上市日期
                item.setStockExchange("sh"); //证券交易所
                item.setStockType("A"); //股票类型
                list.add(item);
            }
        } else if ("sz".equals(stockExchange)) {
            //深交所股票信息
            for (Map<String, Object> m : mapList) {
                Object[] itemArray = m.values().toArray();
                StockInfoEntity item = new StockInfoEntity();
                item.setStockCode(itemArray[4].toString().trim());//股票code
                item.setStockName(itemArray[5].toString().trim()); //股票名字
                item.setListingDate(itemArray[6].toString().trim()); //上市日期
                item.setStockType("A"); //股票类型
                item.setMarketCapital(Long.valueOf(itemArray[7].toString().trim().replace(",", ""))); //总股本
                item.setNegotiableCapital(Long.valueOf(itemArray[8].toString().trim().replace(",", ""))); //流通股
                item.setIndustry(itemArray[17].toString().trim()); //所属行业
                item.setStockExchange("sz"); //证券交易所
                item.setWebsite(itemArray[18].toString().trim());  //公司网址
                list.add(item);
            }
        }

        stockInfoService.importStockInfo(list);

        return R.ok("成功导入股票信息");
    }

}
